/**
 * Created by Administrator on 2018/11/26 0026.
 */
layui.use(['layer','commons','form','laydate','element','table'],function() {
    var layer = layui.layer,
        $ = layui.jquery,
        common = layui.commons,
        form = layui.form,
        laydate = layui.laydate,
        table = layui.table,
        element = layui.element;

    //表单日期初始化
    laydate.render({
        elem:'#test'
    });
    //选项卡监听
    element.on('tab(tab)', function(data){
        serviceOrderBackPage({},data.index)
    });
    //获取（床号,给药途径）菜单列表
    function getPatientInfo(url,obj,data,type,id,name){
        common.ajax(url,data,function(data){
            if(data.status == 0){
                var option = '<option value="">--请选择--</option>';
                for(var i=0;i<data.data.length;i++){
                    option+='<option value="'+data.data[i][id]+'">'+data.data[i][name]+'</option>'
                }
                obj.append(option);
                form.render('select')
            }
        },type)
    }
    //床号菜单列表
    getPatientInfo('./print/getPatientInfo',$('#bedCode'),JSON.stringify({wardId:'22'}),'post','bed_code','pat_name');
    //给药途径菜单列表
    getPatientInfo('./print/getChannel',$('#channel'),'','get','id','name');
    //表格初始化
    function serviceOrderBackPage(obj,isPrint){
        var par = {
            wardId:'59',
            isPrint:isPrint || 0,
            channel:obj.channel || '',
            date:obj.date || '',
            bedCode:obj.bedCode || ''
        };
        var arr = [[
            {type: 'checkbox'},
            {field:'bedCode', title:'床号'},
            {field:'patName', title:'姓名'},
            {field:'admid', title:'住院号'},
            {field:'ordContent', title:'医嘱内容'},
            {field:'channel', title:'给药途径'},
            {field:'frequency', title:'执行频率'},
            {field:'preExcuteDate', title:'执行时间'},
            {field:'printDate', title:'打印时间'},
            {field:'Status', title:'状态'},
        ]];
        if(par.isPrint == 0){
            arr[0].splice(8,1) ;
        }
        common.table('#table','./print/listAll',par,arr,10,'post',function(res){
                $('.layui-tab-title .layui-badge').text(res.data.total);
                for(var i=0;i<res.data.list.length;i++){
                    if(res.data.list[i].printStatus == 0){
                        res.data.list[i].Status = '未打印';
                    }else{
                        res.data.list[i].Status = '已打印';
                    }
                    // switch (res.data.list[i].channel){
                    //     case 1:
                    //         res.data.list[i].channel = '';
                    //         break;
                    //     case 1:
                    //         break;
                    //     case 1:
                    //         break;
                    //
                    // }
                }
                return{
                    data:res.data.list,
                    code:res.status,
                    msg:res.msg,
                    total:res.data.total
                }
            },'#toolbarDemo',[]
        );
    }
    serviceOrderBackPage({});
    //中文字符处理
    function toUtf8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

    //生成二维码
    function outputQRCod(txt, width, height,obj) {
        //中文格式转换
        var str = toUtf8(txt);
        //生成二维码
        obj.qrcode({
            render: "canvas",
            width: width,
            height: height,
            text: str
        });
    }
    //头工具栏事件
    table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id).data;
        var workid = '';
        for(var i=0;i<checkStatus.length;i++){
            workid = workid+checkStatus[i].workid+','
        }
        workid = workid.substr(0,workid.length-1);
        if(checkStatus.length>0){
            common.ajax('./print/printExcute',JSON.stringify({'excuteName':'1','workId':workid}),function(data){
                if(data.status == 0){
                    console.log()
                    var p = ''
                    for(var i = 0;i<data.data.length;i++){
                        for(var j = 0;j<JSON.parse(data.data[i].item).length;j++){
                            p+='<p style="padding-left: 10px">'+'['+JSON.parse(data.data[i].item)[j].spec+JSON.parse(data.data[i].item)[j].unit+JSON.parse(data.data[i].item)[j].name+']'+'</p>'
                        }
                        var tr = '<tr><td style="" class="code code'+i+'"><table><tbody><tr><td>'+data.data[i].deptName+'</td><td style="text-align: right;width: 220px;font-size: 20px">'+data.data[i].frequency+'</td></tr><tr><td><img style="width: 100px;height: 100px" class= "image image'+i+'" src="" alt=""></td><td valign="top">'+p+'</td></tr><tr><td style="font-size: 18px">'+data.data[i].type+'</td></tr><tr><td><h2 style="font-size: 24px">'+data.data[i].bedCode+'<span style="font-size: 12px;margin-left: 6px">'+'慢'+'</span></span></h2></td><td style="font-size: 14px;padding-left: 30px">'+'日期：'+data.data[i].executeDate+'</td></tr><tr><td style="font-size: 18px">'+data.data[i].patName+'</td><td style="font-size: 14px;padding-left: 30px">'+'频次：1'+'</td></tr></td></tr></tbody></table></td></tr>';
                        $('.codeBox .box>tbody').append(tr);
                        p = '';
                        outputQRCod(data.data[i].scanNo, 200, 200,$(".code"+i));
                        var img = document.getElementsByClassName("image"+i);
                        var canvas  = document.getElementsByTagName("canvas")[i];
                        $(".image"+i).attr('src',canvas.toDataURL())
                    }
                    layer.confirm($('.codeBox').html(), {
                        btn: ['打印', '关闭'],
                        area: ['auto', '80%']
                    }, function () {
                        $(".codeBox .box").jqprint({
                            debug: false,
                            importCSS: true,
                            printContainer: true,
                            operaSupport: false
                        });
                        $('.codeBox .box>tbody').html('');
                    },function(){
                        $('.codeBox .box>tbody').html('');
                    })
                }
            },'post');
        }else{
            layer.msg('至少需要勾选一项',{icon:5})
        }
    });
    //表格复选框监听
    table.on('checkbox(test)', function(obj){
        var input = $('.layui-table tbody input');
        var n=1;
        for(var i = 0;i<input.length;i++){
            if($(input[i]).is(':checked')){
                n++
            }
        }
        $('.num').text(n>10?(n-1)/2:n-1)
    });
    //表单提交
    form.on('submit(formDemo)',function(data){
        console.log(data.field);
        serviceOrderBackPage(data.field);
        return false;
    })
});